<template>
  <div>
    <div class="news-container">
      <el-table
        :data="newsList"
        style="width: 100%"
        v-if="newsList.length > 0"
        @row-click="goToDetail"
        highlight-current-row
      >
        <el-table-column
          prop="title"
          label="标题"
          width="300"
        ></el-table-column>
        <el-table-column label="内容" width="560">
          <template #default="scope">
            <div
              class="content-cell"
              :title="'点击查看'"
              @click="goToDetail(scope.row)"
              style="
                cursor: pointer;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              "
            >
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="creattime"
          label="发布时间"
          width="180"
        ></el-table-column>

        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              v-if="userid === scope.row.userid"
              size="mini"
              @click.stop="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="userid === scope.row.userid"
              size="mini"
              type="danger"
              @click.stop="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-data">暂无数据</div>
    </div>

    <!-- 编辑新闻对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑新闻" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="正文">
          <el-input v-model="editForm.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import api from "@/util/service";
import { useLoginStore } from "@/stores/userStores";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const userStore = useLoginStore();
const userid = userStore.getId;
const newsList = ref([]);
const router = useRouter();
const editDialogVisible = ref(false);
const editForm = ref({
  newsid: "",
  userid: "",
  title: "",
  content: "",
});
const currentRow = ref({});

// 使用computed获取用户ID
const currentUserid = computed(() => userStore.getId);

onMounted(() => {
  fetchNews();
});

const fetchNews = async () => {
  try {
    const response = await api.get("/tnews/selectNews");
    if (response.code === 200) {
      newsList.value = response.data;
    }
  } catch (error) {
    console.error("Failed to fetch news:", error);
  }
};

const goToDetail = (row) => {
  sessionStorage.setItem("news", row.newsid);
  router.push("NewsDetail");
};

const handleEdit = async (index, row) => {
  // 编辑逻辑
  currentRow.value = row;
  editForm.value.newsid = row.newsid;
  editForm.value.userid = userid.value;
  editForm.value.title = row.title;
  editForm.value.content = row.content;
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  try {
    const res = await api.post("/tnews/updateNews", editForm.value);
    if (res.code === 200) {
      ElMessage({
        message: "修改成功!",
        type: "success",
      });
      editDialogVisible.value = false;
      fetchNews();
    } else {
      ElMessage({
        message: "修改失败!",
        type: "error",
      });
    }
  } catch (error) {
    ElMessage({
      message: "修改失败!",
      type: "error",
    });
  }
};

const handleDelete = async (index, row) => {
  const params = { newsid: row.newsid };
  const res = await api.post("/tnews/deleteNews", params);
  if (res.code === 200) {
    ElMessage({
      message: "删除成功!",
      type: "success",
    });
    fetchNews();
  } else {
    ElMessage({
      message: "删除失败!",
      type: "error",
    });
  }
};
</script>

<style scoped>
.news-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.no-data {
  font-size: 18px;
  color: #999;
  text-align: center;
  padding: 50px 0;
}

/* 内容单元格样式 */
.content-cell {
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
